import 'package:flutter/material.dart';

class ColorDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('MaterialColor Demo')),
      body: ListView(
        children: <Widget>[
          //背景为蓝色，则title自动为白色
          NavBar(color: Colors.blue, title: "标题"),
          //背景为白色，则title自动为黑色
          NavBar(color: Colors.white, title: "标题"),
          Padding(padding: EdgeInsets.all(20)),
          _buildColorTile('Blue', Colors.blue),
          _buildColorTile('Red', Colors.red),
          _buildColorTile('Green', Colors.green),
          _buildColorTile('Yellow', Colors.yellow),
          _buildColorTile('Orange', Colors.orange),
          _buildColorTile('Purple', Colors.purple),
          _buildColorTile('Pink', Colors.pink),
          _buildColorTile('Teal', Colors.teal),
          _buildColorTile('Cyan', Colors.cyan),
          _buildColorTile('Amber', Colors.amber),
          _buildColorTile('Indigo', Colors.indigo),
          _buildColorTile('Lime', Colors.lime),
          _buildColorTile('Brown', Colors.brown),
          _buildColorTile('Grey', Colors.grey),
          _buildColorTile('Blue Grey', Colors.blueGrey),
        ],
      ),
    );
  }

  Widget _buildColorTile(String colorName, MaterialColor color) {
    return ListTile(
      title: Text(colorName),
      tileColor: color[100],
      trailing: Container(
        width: 50,
        height: 50,
        color: color[500],
      ),
    );
  }
}

// 实现一个背景颜色和Title可以自定义的导航栏，并且:
// 背景色为深色时我们应该让Title显示为浅色；
// 背景色为浅色时，Title 显示为深色
class NavBar extends StatelessWidget {
  final String title;
  final Color color; //背景颜色

  NavBar({Key? key, required this.color, required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(minHeight: 52, minWidth: double.infinity),
      decoration: BoxDecoration(
        color: color,
        boxShadow: [
          //阴影
          BoxShadow(color: Colors.black26, offset: Offset(0, 3), blurRadius: 3),
        ],
      ),
      child: Text(
        title,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          //根据背景色亮度来确定Title颜色
          color: color.computeLuminance() < 0.5 ? Colors.white : Colors.black,
        ),
      ),
      alignment: Alignment.center,
    );
  }
}
